package com.atguigu.gmall.cart.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.consts.GmallConsts;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class CartMqListener {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "cart.queue"),
                    exchange = @Exchange(value = GmallConsts.MQ_ORDER_EXCHANGE
                        ,type = ExchangeTypes.TOPIC),
                    key = "cart.del"
            )
    })
    public void delCartInfos(Map<String,String> map , Message message, Channel channel) throws IOException {
        try {
            //消费者业务
            if(CollectionUtils.isEmpty(map)){
                channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
                return;
            }
            String userId = map.get("userId");
            String skuIds = map.get("skuIds");
            BoundHashOperations<String, String, String> hashOps = stringRedisTemplate
                    .boundHashOps(GmallConsts.CART_PREFIX+userId);
            List<String> skuIdList = JSON.parseArray(skuIds, String.class);
            hashOps.delete(skuIdList.toArray());
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            //e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                //消息第二次消费失败: 丢弃消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                //消息第一次消费失败
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }

}
